/* Copyright (c) 2011 by Mani Brundha Kattamuri, Haritha Subramanyam
 *
 * Project Info:  http://code.google.com/p/andriod-travelapp-csc780/wiki/Design
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 */
package com.example.TravelApp.search.common.helper;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.example.TravelApp.constants.MapConstants;
import com.example.TravelApp.search.common.PlaceObject;

/**
 * This is a helper class that contains static methods that send request to
 * Google Places and retrieve places based on the users selection of interest
 * and location. The second method parses the JSON response and returns a list
 * of place objects that contain information such as venue name, addrress,
 * rating, url about each place returned by Google Places. These methods are
 * called by both Quick search and Advanced Search.
 * 
 * @author Haritha Subramanyam, Mani Brundha
 * 
 */
public class JSONParseHelper implements MapConstants {

	/**
	 * Sends request to Google Places and retrieve places based on the users
	 * selection of interest and location.A URL is constructed and a HTTPGet
	 * request is made.
	 * 
	 * @param location
	 *            - Area/Location of interest
	 * @param radius
	 *            - radius within which places can be included
	 * @param types
	 *            - correspond to interest
	 * @param name
	 *            - name of the place in particular; usually null
	 * @param sensor
	 *            - false
	 * @return jsonObject - JSON response object
	 */
	public static JSONObject getLocationInfo(String location, String radius,
			String types, String name, String sensor) {
		// Construct URL
		String queryString = GOOGLE_PLACES_URL + location
				+ GOOGLE_PLACES_RADIUS + radius + GOOGLE_PLACES_TYPES + types
				+ GOOGLE_PLACES_NAME + name + GOOGLE_PLACES_SENSOR + sensor
				+ GOOGLE_PLACES_KEY;
		// Send request to Google Places
		HttpGet httpGet = new HttpGet(queryString);
		HttpClient client = new DefaultHttpClient();

		HttpResponse response;
		StringBuilder stringBuilder = new StringBuilder();
		// Receive the JSON response and return to the caller
		try {
			response = client.execute(httpGet);

			HttpEntity entity = response.getEntity();
			InputStream stream = entity.getContent();
			int b;
			while ((b = stream.read()) != -1) {
				stringBuilder.append((char) b);
			}
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}

		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject = new JSONObject(stringBuilder.toString());
		} catch (JSONException e) {
			// JSON exceptions are logged and ignored. Usually found due to null
			// values for rating
			// and other information
			Log.e("log_JSON_tag", "Error in recieving response" + e.toString());
		}

		return jsonObject;
	}

	/**
	 * Parses the JSON object and retuns a list of place objects that contain
	 * information about each of the places found in the JSON object.
	 * 
	 * @param json
	 *            - JSON Object to be parsed
	 * @return list - list of place objects; null if no results
	 */
	public static ArrayList<PlaceObject> getList(JSONObject json) {
		try {
			// Convert JSON object to array
			JSONArray results = json.getJSONArray("results");
			ArrayList<PlaceObject> list = new ArrayList<PlaceObject>();
			PlaceObject loc;
			// Iterate through the array and add to the list
			for (int i = 0; i < results.length(); i++) {
				JSONObject jsonCurLocation = results.getJSONObject(i);
				loc = new PlaceObject(jsonCurLocation);
				list.add(i, loc);
			}
			return list;
		} catch (JSONException e) {
			// Null result handled by the caller; User notified that the
			// selection has no results
			Log.e("log_list_tag", "Error in parsing JSON" + e.toString());
		}

		return null;
	}

}
